"""
带外管理编辑对话框
"""

import logging
from PyQt5.QtWidgets import (
    QVBoxLayout, QHBoxLayout, QFormLayout, QLabel, QLineEdit, 
    QPushButton, QComboBox, QTextEdit, QMessageBox, QWidget
)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

try:
    from src.app.ui.base_dialog import BaseDialog
    from src.app.modules.oob.service import OobService
    from src.app.modules.oob.utils import OobUtils
except ImportError:
    # 尝试相对导入
    try:
        from ...ui.base_dialog import BaseDialog
        from ..service import OobService
        from ..utils import OobUtils
    except ImportError as e:
        logger.error(f"导入带外管理对话框依赖失败: {e}")
        raise

logger = logging.getLogger(__name__)

class OobDialog(BaseDialog):
    """带外管理编辑对话框"""
    
    def __init__(self, parent=None, oob_id=None):
        self.oob_id = oob_id
        self.is_edit = oob_id is not None
        self.service = OobService()
        self.utils = OobUtils()
        
        title = "编辑带外管理" if self.is_edit else "新增带外管理"
        super().__init__(parent, title=title, width=600, height=400)
        
        # 如果是编辑模式，加载数据
        if self.is_edit:
            self.load_oob_data()
    
    def create_content_widget(self):
        """创建内容区域 - 重写父类方法"""
        content_widget = QWidget()
        layout = QVBoxLayout(content_widget)
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 带外管理ID（只读）
        self.oob_id_edit = QLineEdit()
        self.oob_id_edit.setReadOnly(True)
        self.oob_id_edit.setPlaceholderText("系统自动生成")
        form_layout.addRow("带外管理ID:", self.oob_id_edit)
        
        # 设备资产选择
        asset_layout = QHBoxLayout()
        self.asset_combo = QComboBox()
        self.asset_combo.setMinimumWidth(300)
        self.refresh_asset_button = QPushButton("刷新")
        self.refresh_asset_button.clicked.connect(self.refresh_assets)
        asset_layout.addWidget(self.asset_combo)
        asset_layout.addWidget(self.refresh_asset_button)
        form_layout.addRow("设备资产:", asset_layout)
        
        # 登录URL
        self.login_url_edit = QLineEdit()
        self.login_url_edit.setPlaceholderText("请输入带外管理登录URL，如：https://192.168.1.100")
        form_layout.addRow("登录URL:", self.login_url_edit)
        
        # 带外类型（自动判断，只读）
        self.oob_type_edit = QLineEdit()
        self.oob_type_edit.setReadOnly(True)
        self.oob_type_edit.setPlaceholderText("根据URL自动判断")
        form_layout.addRow("带外类型:", self.oob_type_edit)
        
        # 详情信息
        self.details_text = QTextEdit()
        self.details_text.setMaximumHeight(100)
        self.details_text.setPlaceholderText("备注信息（可选）")
        form_layout.addRow("备注信息:", self.details_text)
        
        layout.addLayout(form_layout)
        
        # 连接信号
        self.login_url_edit.textChanged.connect(self.on_url_changed)
        
        # 初始化设备列表
        self.refresh_assets()
        
        return content_widget
    
    def refresh_assets(self):
        """刷新设备资产列表"""
        try:
            # 获取没有带外管理的设备列表
            if not self.is_edit:
                assets = self.service.get_asset_without_oob()
                self.asset_combo.clear()
                self.asset_combo.addItem("请选择设备资产", None)
                
                for asset in assets:
                    display_text = f"{asset['asset_id']} - {asset['asset_name']} ({asset['asset_type']})"
                    self.asset_combo.addItem(display_text, asset['asset_id'])
            else:
                # 编辑模式，获取所有设备
                from src.app.database.database import get_database_manager
                from src.app.database.models import Asset
                
                db_manager = get_database_manager()
                with db_manager.get_session() as session:
                    assets = session.query(Asset).all()
                    self.asset_combo.clear()
                    
                    for asset in assets:
                        display_text = f"{asset.asset_id} - {asset.asset_name} ({asset.asset_type})"
                        self.asset_combo.addItem(display_text, asset.asset_id)
                        
        except Exception as e:
            logger.error(f"刷新设备资产列表失败: {str(e)}")
            QMessageBox.warning(self, "警告", f"刷新设备资产列表失败: {str(e)}")
    
    def on_url_changed(self):
        """URL改变时自动判断带外类型"""
        url = self.login_url_edit.text().strip()
        if url:
            oob_type = self.utils.get_oob_type_from_url(url)
            self.oob_type_edit.setText(oob_type)
        else:
            self.oob_type_edit.setText("")
    
    def load_oob_data(self):
        """加载带外管理数据"""
        try:
            result = self.service.get_oob_by_id(self.oob_id)
            if not result['success']:
                QMessageBox.warning(self, "警告", result['message'])
                self.reject()
                return
            
            oob_data = result['data']
            
            # 填充表单
            self.oob_id_edit.setText(oob_data.get('oob_id', ''))
            self.login_url_edit.setText(oob_data.get('login_url', ''))
            
            # 设置设备资产
            asset_id = oob_data.get('asset_id', '')
            for i in range(self.asset_combo.count()):
                if self.asset_combo.itemData(i) == asset_id:
                    self.asset_combo.setCurrentIndex(i)
                    break
            
            # 触发URL变化事件
            self.on_url_changed()
            
        except Exception as e:
            logger.error(f"加载带外管理数据失败: {str(e)}")
            QMessageBox.warning(self, "警告", f"加载数据失败: {str(e)}")
            self.reject()
    
    def get_form_data(self):
        """获取表单数据"""
        asset_id = self.asset_combo.currentData()
        if not asset_id:
            return None, "请选择设备资产"
        
        login_url = self.login_url_edit.text().strip()
        if not login_url:
            return None, "请输入登录URL"
        
        oob_data = {
            'oob_id': self.oob_id_edit.text().strip() or None,
            'asset_id': asset_id,
            'login_url': login_url,
            'details': self.details_text.toPlainText().strip()
        }
        
        return oob_data, ""
    
    def validate_form(self):
        """验证表单"""
        oob_data, error_msg = self.get_form_data()
        if error_msg:
            QMessageBox.warning(self, "验证失败", error_msg)
            return False
        
        # 使用工具类验证数据
        is_valid, validation_error = self.utils.validate_oob_data(oob_data)
        if not is_valid:
            QMessageBox.warning(self, "验证失败", validation_error)
            return False
        
        return True
    
    def save_data(self):
        """保存数据"""
        if not self.validate_form():
            return
        
        oob_data, _ = self.get_form_data()
        
        try:
            if self.is_edit:
                # 更新
                result = self.service.update_oob(self.oob_id, oob_data)
            else:
                # 创建
                result = self.service.create_oob(oob_data)
            
            if result['success']:
                QMessageBox.information(self, "成功", result['message'])
                self.data_saved.emit(result.get('data'))
                self.accept()
            else:
                QMessageBox.warning(self, "警告", result['message'])
                
        except Exception as e:
            logger.error(f"保存带外管理数据失败: {str(e)}")
            QMessageBox.warning(self, "警告", f"保存失败: {str(e)}")
    
    def accept_data(self):
        """重写父类方法 - 处理确定按钮点击"""
        self.save_data()